package com.ruoyi.system.service.impl;

import java.util.List;

import com.ruoyi.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.security.Md5Utils;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysConfigService;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.SysPurchasingunitMapper;
import com.ruoyi.system.domain.SysPurchasingunit;
import com.ruoyi.system.service.ISysPurchasingunitService;
import com.ruoyi.common.core.text.Convert;

/**
 * 采购单位Service业务层处理
 * 
 * @author ruoyi
 * @date 2020-12-13
 */
@Service
public class SysPurchasingunitServiceImpl implements ISysPurchasingunitService 
{
    private static final Logger log = LoggerFactory.getLogger(SysPurchasingunitServiceImpl.class);

    @Autowired
    private SysPurchasingunitMapper sysPurchasingunitMapper;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private SysUserMapper userMapper;


    /**
     * 查询采购单位
     * 
     * @param purchasingUnitId 采购单位ID
     * @return 采购单位
     */
    @Override
    public SysPurchasingunit selectSysPurchasingunitById(Long purchasingUnitId)
    {
        return sysPurchasingunitMapper.selectSysPurchasingunitById(purchasingUnitId);
    }

    /**
     * 查询采购单位列表
     * 
     * @param sysPurchasingunit 采购单位
     * @return 采购单位
     */
    @Override
    public List<SysPurchasingunit> selectSysPurchasingunitList(SysPurchasingunit sysPurchasingunit)
    {
        return sysPurchasingunitMapper.selectSysPurchasingunitList(sysPurchasingunit);
    }

    /**
     * 新增采购单位
     * 
     * @param sysPurchasingunit 采购单位
     * @return 结果
     */
    @Override
    public int insertSysPurchasingunit(SysPurchasingunit sysPurchasingunit)
    {
        sysPurchasingunit.setCreateTime(DateUtils.getNowDate());
        return sysPurchasingunitMapper.insertSysPurchasingunit(sysPurchasingunit);
    }

    /**
     * 修改采购单位
     * 
     * @param sysPurchasingunit 采购单位
     * @return 结果
     */
    @Override
    public int updateSysPurchasingunit(SysPurchasingunit sysPurchasingunit)
    {
        return sysPurchasingunitMapper.updateSysPurchasingunit(sysPurchasingunit);
    }

    /**
     * 删除采购单位对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteSysPurchasingunitByIds(String ids)
    {
        return sysPurchasingunitMapper.deleteSysPurchasingunitByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除采购单位信息
     * 
     * @param purchasingUnitId 采购单位ID
     * @return 结果
     */
    @Override
    public int deleteSysPurchasingunitById(Long purchasingUnitId)
    {
        return sysPurchasingunitMapper.deleteSysPurchasingunitById(purchasingUnitId);
    }

    /**
     * 修改采购单位密码
     * @param sysPurchasingunit
     * @return
     */
    @Override
    public int resetUserPwd(SysPurchasingunit sysPurchasingunit) {
        return sysPurchasingunitMapper.updateSysPurchasingunit(sysPurchasingunit);
    }
    /**
     * 导入采购单位
     * @param userList 采购单位列表
     * @param updateSupport 是否更新现有数据
     * @param operName 操作者名称
     * @return
     */
    public String importUser(List<SysPurchasingunit> userList, boolean updateSupport, String operName){
        if (StringUtils.isNull(userList) || userList.size() == 0)
        {
            throw new BusinessException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        String password = configService.selectConfigByKey("sys.purchasingUnit.initPassword");
        for (SysPurchasingunit user : userList)
        {
            try
            {
                // 验证采购单位表中是否存在这个用户
                SysPurchasingunit su=sysPurchasingunitMapper.selectSysPurchasingunitByAccount(user.getAccount());
                if(StringUtils.isNull(su)){
                    user.setSalt(ShiroUtils.randomSalt());
                    user.setPassword(new Md5Hash(user.getAccount() +  user.getPassword() + user.getSalt()).toHex());
                    user.setCreateBy(ShiroUtils.getLoginName());
                    sysPurchasingunitMapper.insertSysPurchasingunit(user);

                }else{
                    user.setPurchasingUnitId(su.getPurchasingUnitId());
                    sysPurchasingunitMapper.updateSysPurchasingunit(user);
                }


                // 验证系统用户表是否存在这个用户
                SysUser u = userMapper.selectUserByLoginName(user.getAccount());
                SysUser newUser=new SysUser();
                if (StringUtils.isNull(u))
                {

                    newUser.setSalt(user.getSalt());
                    newUser.setPassword(user.getPassword());
                    newUser.setCreateBy(operName);
                    newUser.setPhonenumber(user.getUnitLinkPhone());
                    newUser.setLoginName(user.getAccount());
                    newUser.setUserName(user.getUnitName());
                    newUser.setUserType("10");//10表示采购单位
                    newUser.setCompanyId(user.getPurchasingUnitId());
                    userMapper.insertUser(newUser);
                    Long[] roleIds=new Long[]{2L};
                    userService.insertUserAuth(newUser.getUserId(),roleIds);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getAccount() + " 导入成功");
                }
                else if (updateSupport)
                {
                    u.setSalt(user.getSalt());
                    u.setPassword(user.getPassword());
                    u.setCreateBy(operName);
                    u.setLoginName(user.getAccount());
                    u.setUserName(user.getUnitName());
                    u.setPhonenumber(user.getUnitLinkPhone());
                    u.setUserType("10");//10表示采购单位
                    u.setCompanyId(user.getPurchasingUnitId());
                    userMapper.updateUser(u);
                    Long[] roleIds=new Long[]{2L};
                    userService.insertUserAuth(u.getUserId(),roleIds);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getAccount() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getAccount() + " 已存在");
                }



            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getAccount() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new BusinessException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

}
